<template>
  <div class="user-management">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchParams" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchParams.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchParams.role" placeholder="请选择角色" clearable>
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="访客" value="guest" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <div class="table-header">
        <div class="left-actions">
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
          <el-button 
            type="danger" 
            :disabled="!selectedUsers.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <el-button 
            type="warning" 
            :disabled="!selectedUsers.length"
            @click="handleBatchStatus('inactive')"
          >
            批量禁用
          </el-button>
          <el-button 
            type="success" 
            :disabled="!selectedUsers.length"
            @click="handleBatchStatus('active')"
          >
            批量启用
          </el-button>
        </div>
        <div class="right-actions">
          <el-button @click="refreshData">刷新</el-button>
        </div>
      </div>
      
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">{{ getRoleLabel(row.role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permissions" label="权限">
          <template #default="{ row }">
            <el-tag
              v-for="perm in row.permissions"
              :key="perm"
              size="small"
              class="permission-tag"
            >
              {{ getPermissionLabel(perm) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" size="small" @click="handlePermission(row)">权限</el-button>
            <el-button
              :type="row.status === 'active' ? 'danger' : 'success'"
              size="small"
              @click="handleStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.size"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 权限配置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限配置"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="permissionForm" label-width="100px">
        <el-form-item label="角色">
          <el-select v-model="permissionForm.role" placeholder="请选择角色" @change="handleRoleChange">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="访客" value="guest" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限列表">
          <el-checkbox-group v-model="permissionForm.permissions">
            <el-checkbox
              v-for="perm in filteredPermissions"
              :key="perm.value"
              :label="perm.value"
              :disabled="!isPermissionAvailable(perm.value)"
            >
              {{ perm.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermission">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { SearchParams, TableDataItem, PermissionForm } from '@/types/user';



// 搜索参数
const searchParams = reactive<SearchParams>({
  username: '',
  role: '',
  page: 1,
  size: 10
});

// 表格数据
const tableData = ref<TableDataItem[]>([]);
const loading = ref(false);
const total = ref(0);
const selectedUsers = ref<TableDataItem[]>([]);

// 权限对话框
const permissionDialogVisible = ref(false);
const permissionForm = reactive<PermissionForm>({
  userId: 0,
  role: '',
  permissions: [] as string[]
});

// 角色权限映射
const rolePermissionMap: Record<string, string[]> = {
  admin: ['*'],
  user: ['article:create', 'article:edit'],
  guest: []
};

// 所有可用权限
const allPermissions = [
  { label: '文章管理', value: 'article:manage' },
  { label: '文章创建', value: 'article:create' },
  { label: '文章编辑', value: 'article:edit' },
  { label: '文章删除', value: 'article:delete' },
  { label: '用户管理', value: 'user:manage' },
  { label: '角色管理', value: 'role:manage' },
  { label: '系统设置', value: 'system:setting' }
];

// 根据角色过滤权限
const filteredPermissions = computed(() => {
  if (permissionForm.role === 'admin') {
    return allPermissions;
  }
  return allPermissions.filter(perm => {
    const rolePerms = rolePermissionMap[permissionForm.role] || [];
    return rolePerms.includes('*') || rolePerms.includes(perm.value);
  });
});

// 检查权限是否可用
const isPermissionAvailable = (permission: string) => {
  if (permissionForm.role === 'admin') return true;
  const rolePerms = rolePermissionMap[permissionForm.role] || [];
  return rolePerms.includes('*') || rolePerms.includes(permission);
};

// Mock 数据生成
const generateMockData = (): TableDataItem[] => {
  const roles: Array<'admin' | 'user' | 'guest'> = ['admin', 'user', 'guest'];
  const statuses: Array<'active' | 'inactive'> = ['active', 'inactive'];
  const permissions: string[][] = [
    ['article:create', 'article:edit'],
    ['article:manage'],
    ['user:manage', 'role:manage'],
    ['system:setting'],
    []
  ];

  return Array.from({ length: 50 }, (_, index): TableDataItem => ({
    id: index + 1,
    username: `user${index + 1}`,
    email: `user${index + 1}@example.com`,
    role: roles[Math.floor(Math.random() * roles.length)],
    permissions: permissions[Math.floor(Math.random() * permissions.length)],
    status: statuses[Math.floor(Math.random() * statuses.length)]
  }));
};

// 获取表格数据
const fetchData = async() => {
  loading.value = true;
  try {
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const allData = generateMockData();
    const filteredData = allData.filter(item => {
      return (
        (!searchParams.username || item.username.includes(searchParams.username)) &&
        (!searchParams.role || item.role === searchParams.role)
      );
    });

    total.value = filteredData.length;
    const start = (searchParams.page - 1) * searchParams.size;
    const end = start + searchParams.size;
    tableData.value = filteredData.slice(start, end);
  } catch (error) {
    ElMessage.error('获取数据失败');
    console.log( error);
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  fetchData();
};

// 选择变化
const handleSelectionChange = (selection: TableDataItem[]) => {
  selectedUsers.value = selection;
};

// 批量删除
const handleBatchDelete = async() => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 更新表格数据
    tableData.value = tableData.value.filter(item => 
      !selectedUsers.value.some(selected => selected.id === item.id)
    );
    
    ElMessage.success('批量删除成功');
    selectedUsers.value = [];
  } catch (error) {
    // 用户取消操作
    console.log( error);
  }
};

// 批量状态切换
const handleBatchStatus = async(status: string) => {
  try {
    await ElMessageBox.confirm(
      `确定要${status === 'active' ? '启用' : '禁用'}选中的 ${selectedUsers.value.length} 个用户吗？`,
      `批量${status === 'active' ? '启用' : '禁用'}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 更新表格数据
    selectedUsers.value.forEach(selected => {
      const item = tableData.value.find(item => item.id === selected.id);
      if (item) {
        item.status = status;
      }
    });
    
    ElMessage.success(`批量${status === 'active' ? '启用' : '禁用'}成功`);
    selectedUsers.value = [];
  } catch (error) {
    // 用户取消操作
    console.log( error);
  }
};

// 角色变化处理
const handleRoleChange = (role: string) => {
  const rolePerms = rolePermissionMap[role] || [];
  permissionForm.permissions = rolePerms.includes('*') 
    ? allPermissions.map(p => p.value)
    : rolePerms;
};

// 搜索
const handleSearch = () => {
  searchParams.page = 1;
  fetchData();
};

// 重置
const handleReset = () => {
  searchParams.username = '';
  searchParams.role = '';
  searchParams.page = 1;
  fetchData();
};
// 分页
const handleSizeChange = (val: number) => {
  searchParams.size = val;
  fetchData();
};

const handleCurrentChange = (val: number) => {
  searchParams.page = val;
  fetchData();
};

// 新增用户
const handleAdd = () => {
  ElMessage.info('新增用户功能待实现');
};

// 编辑用户
const handleEdit = (_row: TableDataItem) => {
  ElMessage.info('编辑用户功能待实现');
};

// 权限配置
const handlePermission = (row: TableDataItem) => {
  permissionForm.userId = row.id;
  permissionForm.role = row.role;
  permissionForm.permissions = [...row.permissions];
  permissionDialogVisible.value = true;
};

// 保存权限
const handleSavePermission = async() => {
  try {
    // 模拟 API 请求
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 更新表格数据
    const index = tableData.value.findIndex(item => item.id === permissionForm.userId);
    if (index !== -1) {
      tableData.value[index].role = permissionForm.role;
      tableData.value[index].permissions = [...permissionForm.permissions];
    }
    
    ElMessage.success('权限配置成功');
    permissionDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('权限配置失败');
    console.log( error);
  }
};

// 切换状态
const handleStatus = async(row: TableDataItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 'active' ? '禁用' : '启用'}该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 模拟 API 请求
    await new Promise(resolve => setTimeout(resolve, 500));
    
    row.status = row.status === 'active' ? 'inactive' : 'active';
    ElMessage.success(`${row.status === 'active' ? '启用' : '禁用'}成功`);
  } catch (error) {
    // 用户取消操作
    console.log('操作取消', error);
  }
};

// 辅助函数
const getRoleType = (role: string): string => {
  const types: Record<string, string> = {
    admin: 'danger',
    user: 'success',
    guest: 'info'
  };
  return types[role] || 'info';
};

const getRoleLabel = (role: string): string => {
  const labels: Record<string, string> = {
    admin: '管理员',
    user: '普通用户',
    guest: '访客'
  };
  return labels[role] || role;
};

const getPermissionLabel = (perm: string): string => {
  const permission = allPermissions.find(p => p.value === perm);
  return permission?.label || perm;
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions {
  display: flex;
  gap: 10px;
}

.right-actions {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.permission-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}
</style>
